import nodeResolve from '@rollup/plugin-node-resolve'
import fse from 'fs-extra'
import { defineConfig } from 'rollup'
import { terser } from 'rollup-plugin-terser'
import ts from 'rollup-plugin-ts'
import json from '@rollup/plugin-json'

const input = {
  index: 'src/index.ts'
}

const workerEntryInput = {
  'worker-entry': 'src/manager/worker-entry.ts'
}

export default defineConfig([
  {
    input,
    output: [
      {
        format: 'cjs',
        dir: 'dist',
        sourcemap: true,
        sourcemapExcludeSources: true,
        hoistTransitiveImports: false,
        entryFileNames: '[name].js',
        chunkFileNames: 'private/chunk-[hash].js'
      },
      {
        format: 'es',
        dir: 'dist',
        sourcemap: true,
        sourcemapExcludeSources: true,
        hoistTransitiveImports: false,
        entryFileNames: '[name].mjs',
        chunkFileNames: 'private/chunk-[hash].mjs'
      }
    ],
    plugins: [
      ts({ exclude: ['/node_modules/'] }),
      nodeResolve(),
      json({ preferConst: true }),
      extraPlugin(),
      terser({ keep_classnames: true })
    ]
  },
  {
    input: workerEntryInput,
    output: {
      format: 'es',
      dir: 'dist',
      sourcemap: true,
      sourcemapExcludeSources: true,
      hoistTransitiveImports: false,
      entryFileNames: '[name].mjs'
    },
    plugins: [
      ts({ exclude: ['/node_modules/'], tsconfig: options => ({ ...options, declaration: false }) }),
      nodeResolve(),
      json({ preferConst: true }),
      terser({ keep_classnames: true })
    ]
  }
])

function extraPlugin() {
  return {
    name: 'extra',
    buildEnd() {
      return !this.meta.watchMode && fse.emptyDir('dist')
    },
    generateBundle: (options, bundle) => {
      Object.keys(bundle)
        .filter(f => /\.d\.mts$/.test(f) || /private[\/\\].*?\.d\.ts$/.test(f))
        .forEach(f => delete bundle[f])
    }
  }
}
